import { error } from '@huntianning/miniprogram/components/ui-message/ui-message.js'
import { toJson } from './data'

export function createRequest (config) {
	config = Object.assign({
		onRequest: null,
		onResponse: null
	}, config)
	/**
	 * 发送请求
	 */
	function request (options) {
		let task = null
		let ps = new Promise((resolve, reject) => {
			if (!options.url) {
				throw new Error('请求地址不能为空')
			}
			options = Object.assign({
				url: null,
				data: null,
				header: null,
				method: null,
				error: null
			}, options)
			if (config.onRequest) {
				config.onRequest(options)
			}
			task = uni.request(Object.assign({}, options, {
				dataType: 'json',
				complete: null,
				sslVerify: false,
				success: (res) => {
					if (res && typeof res.data === 'string') {
						// 兼容订单备忘录不知道为什么note里面出现了“”字符串没有带上转义字符，貌似也会导致后端返回的数据变成字符串了，导致界面不显示
						res.data = res.data.replace(/(,"note":"{)(.*?)(}")/g, (r1, r2, r3, r4, r5) => {
							return r2 + (r3.replace(/""/g, '\\"\\"')) + r4
						})
						res.data = toJson(res.data)
					}
					let ps = Promise.resolve()
					if (config.onResponse) {
						ps = config.onResponse(res)
					}
					ps.then(() => {
						if (res && res.data && res.data.code !== 0) {
							if (options.error) {
								options.error(res)
							} else {
								if (res.data.message || res.data.data || res.data.msg) {
									error(res.data.data || res.data.message || res.data.msg)
								} else {
									error('未知请求错误')
								}
							}
							reject(res.data)
						} else {
							resolve(res.data.data)
						}
					}, reject)
				},
				fail: (err) => {
					console.log(err)
					if (err && err.errMsg === 'request:fail abort') {
						reject(err)
					} else {
						if (!options.error) {
							error('请求失败')
						}
						reject(err)
					}
				}
			}))
		})
		ps.abort = () => {
			task && task.abort()
		}
		return ps
	}
	return {
		get (url, data, opts) {
			return request(Object.assign({}, opts, {
				method: 'get',
				url,
				data
			}))
		},
		post (url, data, opts) {
			return request(Object.assign({}, opts, {
				method: 'post',
				url,
				data
			}))
		}
	}
}
